package com.gmlive.common.gmshare.activity

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.TypedArray
import android.os.Build
import android.os.Bundle
import com.gmlive.common.gmshare.interfaces.ShareConstant.SHARE_STATUS_CANCEL
import com.gmlive.common.gmshare.interfaces.ShareConstant.SHARE_STATUS_COMPLETE
import com.gmlive.common.gmshare.interfaces.ShareConstant.SHARE_STATUS_FAILED
import com.gmlive.common.gmshare.share.WXShare
import com.gmlive.common.gmshare.util.ManifestUtil
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/**
 * Author: xs
 * Create on: 2020/06/18
 * Description: _微信回调的类
 */
open class WXShareEntryActivity : Activity(), IWXAPIEventHandler {

    override fun onCreate(savedInstanceState: Bundle?) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            fixOrientation()
        }
        super.onCreate(savedInstanceState)
        val wxApi = if (WXShare.api == null) initWXApi() else WXShare.api
        try {
            wxApi?.handleIntent(intent, this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        this.finish()
    }

    /**
     * 微信授权
     */
    private fun initWXApi(): IWXAPI? {
        val wxKey = ManifestUtil.getWeixinKey(this)
        val wxApi = WXAPIFactory.createWXAPI(applicationContext, wxKey)
        wxApi?.registerApp(wxKey)
        return wxApi
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        try {
            WXShare.api?.handleIntent(intent, this)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
            finish()
        }
    }

    override fun onReq(req: BaseReq) {}

    override fun onResp(resp: BaseResp) {
        if (resp.type == ConstantsAPI.COMMAND_SENDAUTH) {
            return
        }
        when (resp.errCode) {
            BaseResp.ErrCode.ERR_OK -> WXShare.onResp(SHARE_STATUS_COMPLETE, "")
            BaseResp.ErrCode.ERR_USER_CANCEL -> WXShare.onResp(SHARE_STATUS_CANCEL, "")
            BaseResp.ErrCode.ERR_AUTH_DENIED -> WXShare.onResp(SHARE_STATUS_FAILED, "微信认证失败")
            BaseResp.ErrCode.ERR_UNSUPPORT -> WXShare.onResp(SHARE_STATUS_FAILED, "不支持")
            else -> WXShare.onResp(SHARE_STATUS_FAILED, "未知错误")
        }
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {
            return
        }
        super.setRequestedOrientation(requestedOrientation)
    }

    // 解决8.0崩溃问题
    private fun isTranslucentOrFloating(): Boolean {
        var isTranslucentOrFloating = false
        try {
            val styleableRes = Class.forName("com.android.internal.R\$styleable").getField("Window")[null] as IntArray
            val ta = obtainStyledAttributes(styleableRes)
            val m = ActivityInfo::class.java.getMethod("isTranslucentOrFloating", TypedArray::class.java)
            m.isAccessible = true
            isTranslucentOrFloating = m.invoke(null, ta) as Boolean
            m.isAccessible = false
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return isTranslucentOrFloating
    }

    private fun fixOrientation(): Boolean {
        try {
            val field = Activity::class.java.getDeclaredField("mActivityInfo")
            field.isAccessible = true
            val o = field[this] as ActivityInfo
            o.screenOrientation = -1
            field.isAccessible = false
            return true
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return false
    }
}